import { updateUserUsingPost } from '@/api/userController';
import { ProColumns, ProTable } from '@ant-design/pro-components';
import { message, Modal } from 'antd';
import React from 'react';

interface Props {
  oldData?: API.FunRiceUser;
  visible: boolean;
  columns: ProColumns<API.FunRiceUser>[];
  onSubmit: (values: API.UserAddRequest) => void;
  onCancel: () => void;
}

/**
 * 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: API.UserUpdateRequest) => {
  const hide = message.loading('正在更新');
  try {
    await updateUserUsingPost(fields);
    hide();
    message.success('更新成功');
    return true;
  } catch (error: any) {
    hide();
    message.error('更新失败，' + error.message);
    return false;
  }
};



/**
 * 更新弹窗
 * @param props
 * @constructor
 */
const UpdateModal: React.FC<Props> = (props) => {
  const { oldData, visible, columns, onSubmit, onCancel } = props;

  if (!oldData?.id) {
    return <></>;
  }
//   表单初始化值格式转换
const  initialValues = {...oldData};
  //@ts-ignore
  if(oldData.tags){
    //@ts-ignore
    initialValues.tags = JSON.parse(oldData.tags) || [];
  }

  return (
      <Modal
          destroyOnClose
          title={'更新'}
          open={visible}
          footer={null}
          width={800}  // 设置宽度为800px
          onCancel={() => {
            onCancel?.();
          }}
      >
        <ProTable
            type="form"
            columns={columns}
            form={{
              initialValues: initialValues,
            }}

            onSubmit={async (values: API.UserAddRequest) => {
              const success = await handleUpdate({
                ...values,
                // @ts-ignore
                id: oldData?.id,
              });
              if (success) {
                onSubmit?.(values);
              }
            }}
        />
      </Modal>
  );
};
export default UpdateModal;
